require "Net/drawHandler"
---@class UIDrawPond : UIBase
UIDrawPond = UIBase.New(PanelResNames.UIDrawPond)
local t = UIDrawPond

local ErrorState_None = 0
local ErrorState_NotEnough = 1
local isShowBack = nil

--- 免费召唤倒计时计时器
local mFreeSummonTimerId = nil

-- 召唤状态
local SUMMON_STATE = {
    Normal = 0,  -- 常规消耗
    Time   = 1,  -- 倒计时
    Free   = 2   -- 免费
}

function t.Init(func)
    --t.showType = _type
    --t.sequence = sequence
    --t.index = index
    --t.itemId = itemId
    UIBase.Init(t)
    t.backFunc = func;
end

function t:OnCreate()
    --self.timeText = self:GetChild("time")
    -----@type GList

    self.closeBtn = self:GetChild("back")
    self.title = self:GetChild("title/title")
    self.title.text = getLanguage("WishFountain_Title");
    self.DrawOne = self:GetChild("btndraw1")
    self.DrawOne.title = getLanguage("WishFountain_Summon1_Btn");
    self.DrawTen = self:GetChild("btndraw10")
    self.Chose = self:GetChild("btnchange")
    self.Reset = self:GetChild("reset")
    self.btnJump = self:GetChild("btnJump")
    self.btnJump2 = self:GetChild("btnJump2")
    self.btnAdd = self:GetChild("+")
    self.tips = self:GetChild("tips")
    self.sourceUIobj = self:GetChild("UISourceMultiple");
    self.showSourceController = self:GetController("showSource")
    self.Reset.title = getLanguage("WishFountain_Reset_Btn");
    self.btninfo = self:GetChild("info")
    self.btninfo.title = getLanguage("WishFountain_RewardList_Btn");
    self.btnPond = self:GetChild("btnPond")
    self.btnPond.title = getLanguage("WishFountain_Title");
    self:GetChild("residue").text = getLanguage("WishFountain_RemainingReward");
    self.SumNumText = self:GetChild("rsum"):GetChild("title2")
    self.StandPos = self:GetChild("herodraw")
    self.crystalCallPos = self:GetChild("crystalCall")
    self.CostIcon1 = self:GetChild("btndraw1"):GetChild("cost")
    self.CostIcon2 = self:GetChild("btndraw10"):GetChild("cost")
    self.CostText1 = self:GetChild("btndraw1"):GetChild("num1")
    self.CostText2 = self:GetChild("btndraw10"):GetChild("num1")
    self.iconjinbi = self:GetChild("jinbi")
    self.iconzuanshi = self:GetChild("zuanshi")
    self.jinbinum = self:GetChild("jinbinum")
    self.zuanshinum = self:GetChild("zuanshinum");
    self.HeroNameText = self:GetChild("cheroname"):GetChild("bigName");
    self.effectPos = self:GetChild("effectPos");
    self.resetController = self:GetController("reset");
    self.summonController = self:GetController("summon");
    self.funcController = self:GetController("func");
    self.changeTips = self:GetChild("ChangeTips")
    --self.showShipe1 = self:GetChild("effect_sjqck01").wrapTarget;
    self.showShipe = self:GetChild("effect_sjqck").wrapTarget;
    self.UIDrawAward = self:GetChild("UIDrawAward")
    self.SumNumTextAward = self:GetChild("allnum", self.UIDrawAward)
    self.drawAwardWrapper = self:GetChild("herodraw", self.UIDrawAward)
    self.stateAwardController = self:GetController("state", self.UIDrawAward)
    self.wardTitle = self:GetChild("title",self.UIDrawAward)
    self.wardTip = self:GetChild("residue",self.UIDrawAward)
    self.JumpOutTransition = self:GetTransition("Effect_JumpOut1")
    self.wardTip.text = getLanguage("WishFountain_RemainingReward")
    self.wardTitle.text = getLanguage("WishFountain_RewardList_Title")
    self.dynamicAwardList = self:SetDynamicList(self:GetChild("glist", self.UIDrawAward), self.setData, nil, true, true)
    self.ctrlBtnShow=self:GetController("btnshow")
    self.btnShop=self:GetChild("ShopBtn")
    --self.effectWrapper = GoWrapper.New();
    self.drawCount = 0;
    self.drawWrapper = GoWrapper.New();
    if not UIPackage.GetById("FUI/UICity") then
        AddUIPackageDepend(PanelResNames.UIDrawPond, "FUI/UICity");
        self.isNeedRemovePackage = true;
    end
    --self.ModelSpine = newGComponent("HeroPos", "UICity")
    --
    --self.StandPos:AddChild(self.ModelSpine)
    --self.ModelSpine:SetXY(460,(1920-Screen.height)/2-660)
    --self.ModelSpine:SetScale(1.2,1.2)
    --self.ModelSpine.displayObject.gameObject.transform:Find("RichTextField").gameObject:SetActive(false);

    self:RegisterOnClick(self.DrawOne, self.WishOne)
    self:RegisterOnClick(self.DrawTen, self.WishTen)
    self:RegisterOnClick(self.Chose, self.ChoseBigWin)
    self:RegisterOnClick(self.Reset, self.RestWish)
    self:RegisterOnClick(self.closeBtn, self.ClickClose)
    self:RegisterOnClick(self.btnJump,self.onClickSource)
    self:RegisterOnClick(self.btnJump2,self.onClickSource2)
    self:RegisterOnClick(self.btnAdd,self.onClickAdd)
    self:RegisterOnClick(self.btninfo, self.onClickInfo)
    self:RegisterOnClick(self.btnPond, self.onClickPond)
    self:RegisterOnClick(self.btnShop,self.onClickBtnShop)
    self:RegisterOnClick(self:GetChild("n131"),function()
        logicMgr.UIShowManager.ShowCommonTips("HelpTitle32","HelpDes32","FunctionStory505")
    end)

    self.confCost = decodeJsonStrToTabel(G.dataTable["t_global"]["103"].f_string_value)
    self.confCostItem = logicMgr.ItemManager.getItemConstDatabyModelId(self.confCost[1])
    self:SetIcon(self.CostIcon1, self.confCostItem["icon"])
    self:SetIcon(self.CostIcon2, self.confCostItem["icon"])
    self:SetIcon(self.iconzuanshi, self.confCostItem["icon"])
    self:SetIcon(self.iconjinbi, logicMgr.ItemManager.getItemConstDatabyModelId(1)["icon"])
    --self.iconjinbi:SetScale(1,1);
    --self.iconzuanshi:SetScale(1,1);
    self.itemSList = {}
    for i = 1, 2 do
        local index = "showitem" .. (i)
        local icon = {}
        table.insert(self.itemSList, icon)
        icon.root = self:GetChild(index)
        icon.item = self:GetChild("item", icon.root)
        icon.numLab = self:GetChild("title", icon.root)
        icon.gray = self:GetController("gray", icon.root)
    end


    if self.crystalCallPos then
        self.crystalCallObj = EffectUtil.AddCrystalEffect(self.crystalCallPos, 0.93, 0, 0);
    else
        self.crystalCallObj = false
    end

    self:RegisterEvent(Config.EventType.WishPondSourceChange, self.InitData)
    self:RegisterEvent(Config.EventType.WishGetReward, self.GetReward)
    --self:RegisterEvent(Config.EventType.Fresh_Currency, function ()
    --    self.jinbinum.text = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD);
    --end);
    --self:RegisterEvent(Config.EventType.Fresh_Bag, function ()
    --    self.zuanshinum.text = logicMgr.ItemManager.getItemCountbyModelId(self.confCost[1]);
    --end);
    self:RegisterEvent(Config.EventType.BuyPond, function()
        -- drawHandler.GoReqDrawRewardMessage(self.drawCount);
        self:GoReqDrawRewardMessage(self.drawCount)
    end)
    self:RegisterEvent(Config.EventType.DrawPondUpdate,function()
        if self.CharObj then
            setLayer(self.CharObj, LayerMask.NameToLayer("lihui"));
            self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 3);
            self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_Stencil",1);
        end
    end)
    self.BuyData = {}
    self.ShopGoodID = tonumber(G.dataTable["t_global"]["104"].f_string_value)
    self.BuyData = decodeJsonStrToTabel(G.dataTable["t_shopgoods"][tostring(self.ShopGoodID)].f_Price)[1]
    self.heroExcursion = decodeJsonStrToTabel(G.dataTable["t_global"]["309"].f_string_value)
    Util.PlayAction(self.showShipe, "idle1", true);

    -- 免费单抽相关
    local uiTxtFree = self.DrawOne:GetChild("title2")
    if uiTxtFree ~= nil then
        uiTxtFree.text = getLanguage("Draw_FreeText1")
    end
    self:showFreeSummonTime()
end
function t:Refresh()
    drawHandler.GoReqSendWishInfoMessage();
end
function t:updateBtnShop()
    if self:IsShopOpen() then
        self.ctrlBtnShow.selectedIndex=1
    else
        self.ctrlBtnShow.selectedIndex=0
    end
end
function t:onClickBtnShop()
    --local id=tonumber(G.dataTable["t_global"]["559"].f_int_value)
    self:updateBtnShop()
    if self:IsShopOpen()then
        --logicMgr.CostManager.gotoCostById(id)
        showUI(PanelResNames.UIGiftLink, 6, -1, function()
            t:InitData();
        end, true);
    else
        UISysTips.AddMsg("WishFountain_Tips1")
    end
end
function t:IsShopOpen()
    local id=tonumber(G.dataTable["t_global"]["559"].f_int_value)
    local serverData=logicMgr.CostManager.getCostData(id)

    if serverData == nil or serverData.endTime==nil  or HelperFunc.GetServerTime() > serverData.endTime then
        return false
    elseif HelperFunc.GetServerTime() < serverData.startTime then
        return false
    else
        return true
    end
end
function t:WishOne()
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return 
    end

    if (drawHandler.WishSource.bigRewardID == 0) then
        UISysTips.AddMsg(getLanguage("Wish_NoBigHero"));
        if self.CharObj then
            isShowBack = true
            setLayer(self.CharObj, LayerMask.NameToLayer("UI"));
            self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
        end
        showUI(PanelNames.UIDrawChoose,isShowBack);
        return ;
    end
    if (self.SumNum < 1) then
        UISysTips.AddMsg(getLanguage("CommonPop_Tips20"));
        return ;
    end
    self.drawCount = 1;
    if self.drawCount + logicMgr.HeroManager.getDrawTodayCount(EnumConst.drawType.Pond) > dataTable.getGlobalInt(616) then
        UISysTips.AddMsg(getLanguage("Draw_TimeLimitReached"));
        return ;
    end
    local NowWishBi = logicMgr.ItemManager.getItemCountbyModelId(self.confCost[1]);
    self.spendData = NowWishBi;
    self.lastNum = self.SumNum
    if drawHandler.pondFreeCount == 0 and (NowWishBi < self.drawCount) then
        local NeedBi = (self.drawCount - NowWishBi) * self.BuyData[2]
        self:BuyGoodWish(NeedBi, (self.drawCount - NowWishBi));
        return ;
    end
    -- drawHandler.GoReqDrawRewardMessage(1)
    self:GoReqDrawRewardMessage(1)
end

function t:GoReqDrawRewardMessage( count )
    if self.send_req_draw_reward_message then return  end
    self.send_req_draw_reward_message = true
    drawHandler.GoReqDrawRewardMessage( count )

    utimer.timeCall(function()
        self.send_req_draw_reward_message = nil
    end, 1000, 1);
end

function t:IsShowBtn()
    local ownerHeros = logicMgr.HeroManager.getOwnerHeroList(nil,nil,true)
    for _, v in pairs(ownerHeros) do
        if tonumber(v.partnerModelId) == tonumber(drawHandler.WishSource.bigRewardID) then
            self.Chose.visible = false
            break
        end
    end
end

function t:BuyGoodWish(needcoin, needNum)
    local needMoneyName =  HelperFunc.GetItemNameWithoutColor(getLanguage(dataTable.getRow("t_item", self.BuyData[1])["f_ItemName"]))
    local needItemName = HelperFunc.GetItemNameWithoutColor(getLanguage(dataTable.getRow("t_item", self.confCost[1])["f_ItemName"]))
    local resUrl1 = string.format(getLanguage("CommonPop_IconSetting"),self.BuyData[1] or 1)
    local resUrl2 = string.format(getLanguage("CommonPop_IconSetting"),self.confCost[1] or 1)
    local content1 = resUrl1..needMoneyName .. "x" .. needcoin--数量..货币名称
    local content2 = resUrl2..needItemName .. "x" .. needNum--道具名称..数量
    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
    pop.Init("75", function(b)
        if b then
            local haveMoneyNum = logicMgr.ItemManager.getBagNumByTableID(self.BuyData[1])
            if toNumber(haveMoneyNum) < needcoin then
                UISysTips.AddMsg(needMoneyName .. "不足,无法购买")
                AudioManager.Play(2010)
            else
                local thisItem = nil
                local showData = logicMgr.ShopManager.returnShopData()
                for i = 1, #showData.shopItems do
                    local item = showData.shopItems[i]
                    if item["shopItemModelId"] == tostring(self.ShopGoodID) then
                        thisItem = item;
                        break ;
                    end
                end
                if (thisItem ~= nil) then
                    thisItem["shopId"] = 11000
                    thisItem["num"] = needNum
                    shopHandler.reqBuyShopItem(thisItem);
                end
            end
        else
        end
    end, content1, content2);
end

function t:WishTen()
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return
    end

    if (drawHandler.WishSource.bigRewardID == 0) then
        UISysTips.AddMsg(getLanguage("Wish_NoBigHero"));
        showUI(PanelNames.UI,isShowBack);
        return ;
    end
    if (self.SumNum <= 0) then
        UISysTips.AddMsg(getLanguage("CommonPop_Tips20"));
        return ;
    end

    local NowWishBi = logicMgr.ItemManager.getItemCountbyModelId(self.confCost[1]);
    self.drawCount = 10;
    if self.drawCount > self.SumNum then
        self.drawCount = self.SumNum;
    end
    if self.drawCount + logicMgr.HeroManager.getDrawTodayCount(EnumConst.drawType.Pond) > dataTable.getGlobalInt(616) then
        UISysTips.AddMsg(getLanguage("Draw_TimeLimitReached"));
        return ;
    end
    self.spendData = NowWishBi;
    self.lastNum = self.SumNum
    if (NowWishBi < self.drawCount) then
        local NeedBi = (self.drawCount - NowWishBi) * self.BuyData[2]
        self:BuyGoodWish(NeedBi, (self.drawCount - NowWishBi));
        return ;
    end
    -- drawHandler.GoReqDrawRewardMessage(self.drawCount);
    self:GoReqDrawRewardMessage(self.drawCount)
end

function t:ChoseBigWin()
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return
    end
    if self.CharObj then
        isShowBack = true
        setLayer(self.CharObj, LayerMask.NameToLayer("UI"));
        self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
    end
    showUI(PanelNames.UIDrawChoose,isShowBack);
end

function t:RestWish()
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return
    end

    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
    if (drawHandler.WishSource.drawBigReward == 0) then
        pop.Init("21", function(b)
            if b then
                drawHandler.GoReqResetWishMessage();
                --if self and self.effectObj then
                --    self.effectObj.gameObject:SetActive(false);
                --end
            else
            end
        end);
    else
        pop.Init("22", function(b)
            if b then
                drawHandler.GoReqResetWishMessage();
                --if self and self.effectObj then
                --    self.effectObj.gameObject:SetActive(false);
                --end
            else
            end
        end);
    end

end

function t:InitData()
    local hansNum = logicMgr.ItemManager.getItemCountbyModelId(self.confCost[1])
    self.CostText1.text = hansNum >= 1 and 1 or "[color=#FF0000]1[/color]";


    self.jinbinum.text = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD);
    self.zuanshinum.text = logicMgr.ItemManager.getItemCountbyModelId(self.confCost[1]);
    self.tips.text = string.format(getLanguage("Draw_TimeLimit"), logicMgr.HeroManager.getDrawTodayCount(EnumConst.drawType.Pond), dataTable.getGlobalInt(616));
    --UIRedDots.removeListen("DrawOne");
    --UIRedDots.removeListen("DrawTen");
    UIRedDots.addViewListen(PanelResNames.UIDrawPond, "DrawOne", self.DrawOne, Config.RedDotsType.DrawPond, {1});
    UIRedDots.addViewListen(PanelResNames.UIDrawPond, "DrawTen", self.DrawTen, Config.RedDotsType.DrawPond, {10});
    --self.DrawOne:GetChild("UIRedDots"):SetXY(448, 7)
    --self.DrawTen:GetChild("UIRedDots"):SetXY(448, 7)
    local tConfg = G.dataTable["t_wishfountain"]

    self.ShowKeyTab = {}
    local heroChip = decodeJsonStrToTabel(dataTable.getGlobalString(573));
    self.SumNum = heroChip[2];
    for i = 1, #drawHandler.WishSource.wishRewardInfo do
        local tempWish = drawHandler.WishSource.wishRewardInfo[i]
        if tempWish.type ~= 2 then
            local keyID = tempWish.items[1].itemID;
            local RNum = tempWish.rewardCount;
            self.ShowKeyTab[tostring(keyID)] = RNum;
            self.SumNum = self.SumNum + RNum;
            if tempWish.type == 4 then
                self.SumNum = self.SumNum - heroChip[2];
            end
        end
    end
    if (drawHandler.WishSource.drawBigReward == 0) then
        self.SumNum = self.SumNum + 1;
        self.resetController.selectedIndex = 0;
        self.stateAwardController.selectedIndex = 0;
        self.changeTips.text = getLanguage("WishFountain_ChangeTips")
    else
        self.resetController.selectedIndex = 1;
        self.stateAwardController.selectedIndex = 1;
        self.changeTips.text = getLanguage("WishFountain_ResetTips")
        isShowBack = false
    end
    if self.SumNum == 0 then
        self.DrawTen.title = string.format(getLanguage("WishFountain_SummonX_Btn"), 10);
        self.CostText2.text = hansNum >= 10 and 10 or "[color=#FF0000]10[/color]";
    else
        self.DrawTen.title = string.format(getLanguage("WishFountain_SummonX_Btn"), math.min(10, self.SumNum));
        self.CostText2.text = hansNum >= 10 and 10 or string.format("[color=#FF0000]%s[/color]",math.min(10, self.SumNum));
    end
    local ConfigNum = 0;
    for k, v in pairs(tConfg) do
        local tempPond = decodeJsonStrToTabel(v.f_ItemGroup);
        if (v.f_ItemShowId ~= 0) then
            for i = 1, #tempPond do
                local item = self.itemSList[v.f_ItemShowId]
                local AwardID = tempPond[i][1];
                local iconNum = v.f_ItemGroupNum;
                logicMgr.CostManager.RefreshItem(item.item, tempPond[i])
                item.gray.selectedIndex = 0;
                if (self.ShowKeyTab[tostring(AwardID)] ~= nil) then
                    item.numLab.text = self.ShowKeyTab[tostring(AwardID)] .. "/" .. tostring(iconNum)
                    if self.ShowKeyTab[tostring(AwardID)] == 0 then
                        item.gray.selectedIndex = 1;
                    end
                end
                self:RegisterOnClick(item.root, function()
                    self:onClickitem(AwardID, iconNum)
                end)
            end
        end
        ConfigNum = ConfigNum + v.f_ItemGroupNum;
    end
    ConfigNum = ConfigNum + 1;--大奖数量
    ConfigNum = ConfigNum + heroChip[2];--英雄碎片

    self:ClickInfo();
    self.SumNumText.text = self.SumNum .. "/" .. ConfigNum
    if (drawHandler.WishSource.bigRewardID == 0) then
        if (self.CharObj ~= nil) then
            destroy(self.CharObj.gameObject);
            self.CharObj = nil;
        end
        if self.CharObj then
            isShowBack = true
            setLayer(self.CharObj, LayerMask.NameToLayer("UI"));
            self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
        end
        self.showOpenAni = nil;
        showUI(PanelNames.UIDrawChoose,isShowBack);
        return ;
    end
    if self.showOpenAni then
        self.JumpOutTransition:Play();
        self.showOpenAni = nil;
    end
    if (self.CharObj ~= nil) then
        if (self.CharObj.name == tostring(drawHandler.WishSource.bigRewardID)) then
            return ;
        end
    end
    local _x = 0
    local _y = 0
    local _sx = 1
    local _sy = 1
    for k, v in pairs(self.heroExcursion) do
        if tostring(v[1]) == tostring(drawHandler.WishSource.bigRewardID) then
            local _sRate = (1080 * GRoot.inst.height - 2340 * (GRoot.inst.width-2*Config.uiXOffset))/(840*GRoot.inst.width);
            _sx = _sRate + v[2];
            _sy = _sRate + v[3];
            _x = v[4];
            _y = _sRate * -2 + v[5];
        end
    end

    local imageName = logicMgr.HeroManager.GetHeroDrawingPath(drawHandler.WishSource.bigRewardID)
    if self.resetController.selectedIndex ~= 1 then
        if imageName ~= "" and imageName ~= nil then
            resMgr:LoadModelPrefab(imageName, function(go)
                if (self.CharObj ~= nil) then
                    self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
                    destroyImmediate(self.CharObj);
                end
                self.CharObj = newObject(go);
                self.CharObj.name = imageName;--"CharObj";
                self.CharObj:AddComponent(TCanvas);
                self.drawWrapper:SetWrapTarget(self.CharObj, false)
                Util.Lua_SetLocalPositionXYZ(self.CharObj.transform, 0, 0, 0)
                Util.Lua_SetLocalScaleXYZ(self.CharObj.transform, _sx, _sy, 1) -- 奖励展示界面英雄spine缩放
                self.StandPos:SetNativeObject(self.drawWrapper);
                self.CharObj:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle1", true);
                if self.crystalCallObj then
                    setLayer(self.CharObj, LayerMask.NameToLayer("lihui"));
                    EffectUtil.TranformCrystalEffect(0.93,_x,_y)
                    self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 3);
                    self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_Stencil",1);
                end
                if self.funcController.selectedIndex == 1 then
                    self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
                end
            end);
        end
    end
    self:updateBtnShop()
end

function t:onClickitem(index, num)
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return
    end

    if (index ~= nil) then
        local data = {}
        data = logicMgr.ItemManager.getItemConstDatabyModelId(index);
        data["num"] = num
        showUI(PanelNames.UIBagItemInfo, data, 1);
    end
end

function t:OnEnable()
    SetPlayerPrefsAfter5AMFlag("DrawPondRedDots");
    if RedDotsDrawPondHandler then
        RedDotsDrawPondHandler.update();
    end
    self.showOpenAni = true;
    self.funcController.selectedIndex = 0;
    self.last_select_index = 0
    self:Refresh()
end
function t:OnDisable()
    self.cur_show_reward_state = nil
    self.send_req_draw_reward_message = nil
    if (self.CharObj ~= nil) then
        self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
        destroy(self.CharObj.gameObject);
        self.CharObj = nil;
    end
    if (self.objHeroDraw ~= nil) then
        destroyImmediate(self.objHeroDraw);
        self.objHeroDraw = nil;
    end
    --HelperFunc.UnloadUnusedAssets(EnumConst.ClearType.Prefab)
    --if self.effectObj then
    --    destroyImmediate(self.effectObj.gameObject);
    --    self.effectObj = nil;
    --end
    if t.backFunc then
        t.backFunc();
    end
end
function t:OnDestroy()
    UIRedDots.removeViewEvent(PanelResNames.UIDrawPond);
    if self.isNeedRemovePackage and UIPackage.GetById("FUI/UICity") then
        UIPackage.RemovePackage("FUI/UICity")
    end
    self:removeFreeSummonTimer()
    HelperFunc.UnloadLihui()
end

function t:GetReward(vReward)
    local Dreward = {}
    local showType = 2;
    local showTime = 1800;
    local newPartnerModelId = -1;
    for i = 1, #vReward.items do
        local tempitems = vReward.items[i]
        if tempitems.type ~= 2 then
            for j = 1, #tempitems.itemInfos do
                local singleD = tempitems.itemInfos[j]
                local singlereward = logicMgr.ItemManager.getItemConstDatabyModelId(singleD.itemID)
                singlereward.num = singleD.itemNum
                table.insert(Dreward, singlereward)
                self:sendTAData(singleD.itemID, singleD.itemNum, 0, #vReward.items);
            end
        elseif tempitems.type == 2 then
            --获得英雄
            local _partnerModelId = tostring(drawHandler.WishSource.bigRewardID)
            showType = 3;
            showTime = 3250;
            local singlereward = {};
            local heroData = logicMgr.HeroManager.getHeroDatabyModelId(_partnerModelId,true);
            if heroData ~= nil and heroData.isNew then
                singlereward.itemModelId = 201500 + _partnerModelId
                --singlereward.num = 1;
                logicMgr.HeroManager.setHeroIsNew(heroData.partnerId, false)
                newPartnerModelId = tonumber(_partnerModelId)
            else
                local heroconfig = G.dataTable["t_hero"][tostring(_partnerModelId)];
                singlereward.itemModelId =heroconfig.f_StoneId
                singlereward.num = heroconfig.f_RepeatCount;
            end
            table.insert(Dreward, singlereward);
            self:sendTAData(0, 0, _partnerModelId, #vReward.items);
            --判断是否为新英雄
            local _newHeroData = HeroManager.getHeroDatabyModelId(_partnerModelId,true)
            if _newHeroData and _newHeroData.isNew then
                local _heroSource = TAManager.GetHeroSource.Pond_One
                if #vReward.items == 10 then
                    _heroSource = TAManager.GetHeroSource.Pond_Ten
                end
                HeroManager.SetNewHeroTA(_partnerModelId,_heroSource)
            end
        end
    end

    if showType == 2 then
        AudioManager.Play(4013)
    else
        AudioManager.Play(4014)
    end

    self.summonController.selectedIndex = 1;
    Util.PlayAction(self.showShipe, "idle" .. showType, false);

    self.cur_show_reward_state = true
    self.send_req_draw_reward_message = nil
    utimer.timeCall(function()
        self.cur_show_reward_state = nil
        self.summonController.selectedIndex = 0
        if newPartnerModelId > -1 then
            showUI(PanelNames.UIDrawAnimation, newPartnerModelId, nil, false, function()
                closeUI(PanelNames.UIDrawAnimation);
                if self.SumNum <= 0 then
                    showUI(PanelNames.UICommonItemGet, nil, nil, 2, Dreward, function ()
                        self:ShowReset();
                        logicMgr.FlashGiftManager.showNewFlashGift();
                    end , nil, true);
                else
                    showUI(PanelNames.UICommonItemGet, nil, nil, 2, Dreward, logicMgr.FlashGiftManager.showNewFlashGift, nil, true);
                end
            end, nil, true);
        else
            if self.SumNum <= 0 then
                showUI(PanelNames.UICommonItemGet, nil, nil, 2, Dreward, function ()
                    self:ShowReset();
                end, nil, true);
            else
                showUI(PanelNames.UICommonItemGet, nil, nil, 2, Dreward, nil, nil, true);
            end
        end

        Util.PlayAction(self.showShipe, "idle1", true);
        if self.resetController.selectedIndex == 1 then
            if (self.CharObj ~= nil) then
                self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
                destroy(self.CharObj.gameObject);
                self.CharObj = nil;
                isShowBack = false
            end
        else
            if self.CharObj then
                isShowBack = true
            end
        end
    end, showTime, 1);

    -- 刷新免费单抽数据
    self:showFreeSummonTime()
end

function t:ShowReset()
    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
    pop.Init("20", function(self,b)
        if b then
            drawHandler.GoReqResetWishMessage();
            --if self and self.effectObj then
            --    self.effectObj.gameObject:SetActive(false);
            --end
            if self and self.CharObj then
                isShowBack = true
                setLayer(self.CharObj, LayerMask.NameToLayer("UI"));
                self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
            end
            showUI(PanelNames.UIDrawChoose,isShowBack);
        end
    end);
end

function t:sendTAData(id, num, hero, items)
    local TAData = {};
    --TAData.get_item_id = tostring(id)
    TAData.get_item_number = tonumber(items)
    -- TAData.get_hero_id = tostring(hero)
    self.lastNum = self.lastNum - 1;
    TAData.current_left_number = tonumber(self.lastNum)
    -- if self.spendData > 0 then
    --     TAData.cost_item_id = self.confCost[1];
    --     TAData.cost_item_number = self.confCost[2];
    --     self.spendData = self.spendData - 1;
    -- else
    --     TAData.cost_item_id = self.BuyData[1];
    --     TAData.cost_item_number = self.BuyData[2];
    -- end
    -- TAData.get_consumption_points = logicMgr.ItemManager.GetItemConsumptionPoints(TAData.cost_item_id) * TAData.cost_item_number;
    TAManager.TrackByDictionary("draw_wishfountain", TAData);
end

function t:ClickInfo()
    if drawHandler.WishSource.bigRewardID == 0 then
        return;
    end
    local tConfg = G.dataTable["t_wishfountain"]
    self.ShowKeyAwardTab = {}
    self.ConfigKeyAwardTab = {};

    local showCard = {}
    local SumNum = 0;
    showCard.itemid = 201500 + drawHandler.WishSource.bigRewardID;
    showCard.itemNum = 1;
    if (drawHandler.WishSource.drawBigReward == 0) then
        showCard.num = 1
        SumNum = 1;
    else
        showCard.num = 0
    end
    showCard.heroiD = drawHandler.WishSource.bigRewardID;
    table.insert(self.ShowKeyAwardTab, showCard)
    self.ConfigKeyAwardTab[tostring(showCard.itemid)] = {};
    self.ConfigKeyAwardTab[tostring(showCard.itemid)][tostring(showCard.itemNum)] = 1
    local heroChip = decodeJsonStrToTabel(dataTable.getGlobalString(573));

    local showCard1 = {}
    showCard1.itemid = logicMgr.HeroManager.GetHeroStoneIdByModelId(drawHandler.WishSource.bigRewardID);
    showCard1.itemNum = heroChip[1];
    showCard1.num = heroChip[2]
    for i = 1, #drawHandler.WishSource.wishRewardInfo do
        local tempWish = drawHandler.WishSource.wishRewardInfo[i]
        local RNum = tempWish.rewardCount;
        if (tempWish.type == 1 or tempWish.type == 3) then
            SumNum = SumNum + RNum;
            local showD = {}
            showD.itemid = tempWish.items[1].itemID;
            showD.itemNum = tempWish.items[1].itemNum;
            showD.num = RNum
            table.insert(self.ShowKeyAwardTab, showD)
        elseif tempWish.type == 4 then -- 大奖对应的英雄碎片
            showCard1.num = RNum
        end
    end
    SumNum = SumNum + showCard1.num;
    table.insert(self.ShowKeyAwardTab, 2, showCard1)
    self.ConfigKeyAwardTab[tostring(showCard1.itemid)] = {};
    self.ConfigKeyAwardTab[tostring(showCard1.itemid)][tostring(showCard1.itemNum)] = heroChip[2];

    local ConfigNum = 0;
    for k, v in pairs(tConfg) do
        local tempPond = decodeJsonStrToTabel(v.f_ItemGroup);
        for i = 1, #tempPond do
            local AwardID = tempPond[i][1];
            local iconNum = tempPond[i][2];-- v.f_ItemGroupNum
            self.ConfigKeyAwardTab[tostring(AwardID)] = self.ConfigKeyAwardTab[tostring(AwardID)] or {};
            self.ConfigKeyAwardTab[tostring(AwardID)][tostring(iconNum)] = v.f_ItemGroupNum
        end
        ConfigNum = ConfigNum + v.f_ItemGroupNum;
    end
    ConfigNum = ConfigNum + 1 + heroChip[2];--大奖数量

    self.SumNumTextAward.text = SumNum .. "/" .. ConfigNum

    self.dynamicAwardList.numItems = #self.ShowKeyAwardTab;

    local imageName = logicMgr.HeroManager.GetHeroDrawingPath(drawHandler.WishSource.bigRewardID)
    if imageName ~= "" and imageName ~= nil then
        resMgr:LoadModelPrefab(imageName, function(go)
            if (self.drawWrappers == nil) then
                self.drawWrappers = GoWrapper.New();
            end
            if (self.objHeroDraw ~= nil) then
                destroyImmediate(self.objHeroDraw);
            end
            self.objHeroDraw = newObject(go);
            self.objHeroDraw.name = imageName;--"objHeroDraw";
            self.objHeroDraw:AddComponent(TCanvas);
            self.drawWrappers:SetWrapTarget(self.objHeroDraw, false)
            Util.Lua_SetLocalPositionXYZ(self.objHeroDraw.transform, 0, 0, 0)
            Util.Lua_SetLocalScaleXYZ(self.objHeroDraw.transform, 1, 1, 1) -- 奖励展示界面英雄spine缩放
            self.drawAwardWrapper:SetNativeObject(self.drawWrappers);
            self.objHeroDraw:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle1", true);
        end);
    end
end

function t:setData(index, itemobj)
    local itemValue = self.ShowKeyAwardTab[index];
    local go = itemobj;
    local itemRoot = go:GetChild("item");
    local sum = go:GetChild("sum");
    local itemname = go:GetChild("itemname");
    local gray = go:GetController("gray");
    local ifShowShelves = go:GetController("ifShowShelves");
    local confItem = G.dataTable["t_item"][tostring(itemValue.itemid)]
    logicMgr.CostManager.RefreshItem(itemRoot, { itemValue.itemid, itemValue.itemNum});
    if confItem == nil then
        itemname.text = "";
    else
        itemname.text = getLanguage(confItem.f_ItemName);
    end
    if self.ConfigKeyAwardTab[tostring(itemValue.itemid)] and self.ConfigKeyAwardTab[tostring(itemValue.itemid)][tostring(itemValue.itemNum)] then
        local itemNum = self.ConfigKeyAwardTab[tostring(itemValue.itemid)][tostring(itemValue.itemNum)];
        if itemValue.num == 0 then
            sum.text = table.concat({string.TextColor(itemValue.num,"#FF0000"), "/", itemNum})
        else
            sum.text = table.concat({ itemValue.num, "/", itemNum})
        end
    else
        sum.text = table.concat({ itemValue.num, "/", itemValue.num})
    end
    if itemValue.num == 0 then
        gray.selectedIndex = 1;
    else
        gray.selectedIndex = 0;
    end
    ifShowShelves.selectedIndex = index % 4 == 1 and 1 or 0;
end

function t:onClickPond()
    if self.last_select_index == 0 then
        return
    end
    --if self.cur_show_reward_state or self.send_req_draw_reward_message then  
    --    if self.last_select_index == 1 then
    --        self.funcController.selectedIndex = self.last_select_index
    --    end
    --    return 
    --end

    self.last_select_index = 0
    if self.crystalCallObj then
        setLayer(self.CharObj, LayerMask.NameToLayer("lihui"));
    end
    if self.CharObj then
        self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 3);
        self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_Stencil",1);
    end
end

function t:onClickInfo()
    if self.last_select_index == 1 then
        return
    end
    --if self.cur_show_reward_state or self.send_req_draw_reward_message then  
    --    if self.last_select_index == 0 then
    --        self.funcController.selectedIndex = self.last_select_index
    --   end 
    --    return 
    --end
    self.last_select_index = 1
    if self.CharObj then
        self.CharObj:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
    end
end

function t:ClickClose()
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return
    end
    closeUI(PanelResNames.UIDrawPond)
end

function t:onClickSource()
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return
    end

    self.showSourceController.selectedIndex = 1;
    self.showSourceList = {self.confCost[1]}
    self:updateSource();
end

function t:onClickSource2()
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return
    end

    self.showSourceController.selectedIndex = 1;
    self.showSourceList = {self.confCost[2]}
    self:updateSource();
end

function t:onClickAdd()
    if self.cur_show_reward_state or self.send_req_draw_reward_message then
        return
    end

    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Cost, true, self.btnAdd) then
        logicMgr.CostManager.gotoCostById();
    end
    self:ClickClose();
end

function t:updateSource()
    logicMgr.ItemManager.updateSourceUI(self.sourceUIobj, self.showSourceList, function ()
        self.showSourceController.selectedIndex = 0;
    end, function ()
        self.showSourceController.selectedIndex = 0;
        self:ClickClose();
    end );
end

--- 单抽状态
--- @param state number 状态值
function t:setDrawOneState(state)
    if self.DrawOne == nil then
        return
    end

    --- @type GController
    local stateCtrl = self.DrawOne:GetController("type")
    if stateCtrl == nil then
        return
    end
    stateCtrl.selectedIndex = state
end

--- 免费时间倒计时展示
function t:showFreeSummonTime()
    local this = self
    local uiTxtTime = this.DrawOne:GetChild("time")
    if uiTxtTime == nil then
        return
    end

    local function __checkTimer()
        local leftTime = drawHandler.getDrawPondFreeLeftTime()
        uiTxtTime.text = string.format(getLanguage("Draw_FreeText2"), HelperFunc.GetTimeStr(leftTime))
        if leftTime <= 0 then
            this:onFreeTimerComplete()
        end
    end

    utimer.remove(mFreeSummonTimerId)
    mFreeSummonTimerId  = utimer.timeCall(__checkTimer, 1000, -1)
    this:setDrawOneState(SUMMON_STATE.Time)
    __checkTimer()
end

--- 倒计时完成
function t:onFreeTimerComplete()
    self:removeFreeSummonTimer()
    self:setDrawOneState(SUMMON_STATE.Free)

    -- 数据更新
    if drawHandler.pondFreeCount == 0 then
        drawHandler.pondFreeCount = 1
        FireEvent(Config.EventType.Fresh_Free_Pond)
    end
end

-- 移除计时器
function t:removeFreeSummonTimer()
    if mFreeSummonTimerId == nil then
        return  
    end
    utimer.remove(mFreeSummonTimerId)
    mFreeSummonTimerId = nil
end

return t
